﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace HHXX.EFDAL
{
    public class BaseDal<T> where T : class, new()
    {

        /// <summary>
        /// 依赖抽象编程 变化的时候改变最小
        /// </summary>
        public DbContext Db
        {
            get
            {
                return DbContextFactory.GetCurrentDbContext();
            }
        }

        public T GetModel(int id)
        {

            return Db.Set<T>().Find(id);
        }
        public T GetModel(object id)
        {
            return Db.Set<T>().Find(id);
        }


        public IQueryable<T> GetEntities(Expression<Func<T, bool>> whereLambda)
        {

            return Db.Set<T>().Where(whereLambda).AsQueryable();
        }

        public T Add(T T)
        {
            Db.Set<T>().Add(T);
            //Db.SaveChanges();
            return T;
        }
        public bool Update(T T)
        {
            Db.Entry(T).State = EntityState.Modified;

            //bool res = Db.SaveChanges() > 0;
            return true;
        }
        /// <summary>
        /// 真删除
        /// </summary>
        /// <param name="T"></param>
        /// <returns></returns>
        public bool Delete(T T)
        {
            Db.Entry(T).State = EntityState.Deleted;

            //bool res = Db.SaveChanges() > 0;
            return true;
        }
        public bool IsExist(object id)
        {
            return GetModel((int)id) != null;
        }

        public IQueryable<T> GetPageEntities<S>(int pageSize, int pageIndex, out int total, Expression<Func<T, bool>> whereLambda
            , Expression<Func<T, S>> orderByLambda, bool isAsc)
        {
            total = Db.Set<T>().Where(whereLambda).Count();
            var temp = Db.Set<T>().Where(whereLambda)
                .OrderBy<T, S>(orderByLambda)
                .Skip(pageSize * (pageIndex - 1))
                .Take(pageSize).AsQueryable();
            return temp;
        }
        /// <summary>
        /// 真删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(int id)
        {
            var entity = Db.Set<T>().Find(id);
            Db.Set<T>().Remove(entity);
            return true;
        }
        public int DeleteListByLogical(List<int> ids)
        {
            foreach (var id in ids)
            {
                var entity = Db.Set<T>().Find(id);
                Db.Entry(entity).Property("DelFlag").CurrentValue = 1;
                Db.Entry(entity).Property("DelFlag").IsModified = true;
            }
            return ids.Count;
        }

    }
}
